import React from 'react';
import { Button, Input, Table, Modal, Select, message, Spin } from 'antd';
import Api from 'Utils/api';
import { generateUUID } from 'Utils';
import AddModal from '../Modal/addAccountModal';
import InitialModal from '../Modal/initialModal';
import EqualBorder from './../../../CommonComponents/EqualBorder';
import './index.scss';

const Search = Input.Search;
const confirm = Modal.confirm;
const PAGE_SIZE = 6;
const Option = Select.Option;
class Account extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      dataCount: 0,
      data: [],
      listPage: 1,
      roleList: [],
      isLoading: true,
    };
    this.condition = { offset: 0, limit: PAGE_SIZE };
    this.onAdd = ::this.onAdd;
    this.initRoles = ::this.initRoles;
    this.initList = ::this.initList;
    this.selectRoles = ::this.selectRoles;
    this.generatorColumns = ::this.generatorColumns;
  }
  componentDidMount() {
    this.initRoles();
    this.initList();
  }
  initRoles() {
    const api = new Api({
      method: 'GET',
      path: '/roles',
      success: (json) => {
        console.log(json);
        this.setState({ roleList: json.data_list });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initList() {
    const api = new Api({
      method: 'GET',
      path: '/accounts',
      query: { ...this.condition },
      success: (json) => {
        this.setState({ isLoading: false, listPage: ((this.condition.offset / PAGE_SIZE) + 1), data: json.data_list, dataCount: json.total_count });
      },
      error: (msg) => {
        this.setState({
          isLoading: false
        });
        message.error(msg);
      }
    });
    api.run();
  }
  onListPageChange(page) {
    this.setState({ listPage: page, isLoading: true }, this.initList.bind(this));
    this.condition.offset = (page - 1) * PAGE_SIZE;
  }
  generatorColumns() {
    return [
      {
        title: '序号',
        dataIndex: 'key',
        width: '5%',
        render: (text, record, index) => {
          return (<span>{((this.state.listPage - 1) * PAGE_SIZE) + (index + 1)}</span>);
        }
      },
      {
        title: '用户名',
        dataIndex: 'username',
        width: '10%',
        render: text => (
          <span >{text}</span >
        )
      },
      {
        title: '昵称',
        width: '10%',
        dataIndex: 'nickname',
        render: text => (
          <span >{text}</span >
        )
      }, {
        title: '部门',
        dataIndex: 'dept',
        width: '15%',
        render: text => (
          <span >{text}</span >
        )
      },
      {
        title: '角色名称',
        dataIndex: 'roles',
        width: '42%',
        render: (text) => {
          const len = text.length;
          if (len > 0) {
            return (<span>
              {
                text.map(item => <span key={generateUUID()}>{item.name}&nbsp;&nbsp;</span>)
              }
            </span >);
          }
          return <span />;
        }
      },
      {
        title: '操作',
        dataIndex: 'operate',
        width: '18%',
        render: (text, record) => (
          <span className="operate">
            <span className="edit" style={{ color: '#F6A87F' }} onClick={this.onAdd.bind(this, record)}>修改</span >
            <span className="delete" onClick={this.handleDelete.bind(this, record)} style={{ color: '#F45757' }}>删除</span >
            <span style={{ color: '#00D8FE' }} onClick={this.onInitial.bind(this, record)}>恢复初始密码</span>
          </span>
        )
      }
    ];
  }
  onInitial(record) {
    this.InitialModal.showModal(record);
  }
  onAdd(record) {
    this.AddModal.showModal(record);
  }
  handleDelete(record) {
    const self = this;
    confirm({
      title: '删除',
      content: '确定删除该账号吗？',
      onOk() {
        self.setState({
          isLoading: true,
        });
        const api = new Api({
          method: 'DELETE',
          path: `/accounts/${record.id}`,
          success: () => {
            self.initList();
          },
          error: (msg) => {
            message.error(msg);
          }
        });
        api.run();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  selectRoles(id) {
    this.condition = Object.assign(this.condition, { role_id: id });
    this.setState({
      isLoading: true,
    });
    this.initList();
  }
  handleSearch(value) {
    this.condition = Object.assign(this.condition, { name_like: value });
    this.setState({
      isLoading: true,
    });
    this.initList();
  }
  render() {
    const columns = this.generatorColumns();
    return (
      <div>
        <EqualBorder
          content={
            <div className="account-project-wrap">
              <div className="account-header">
                <Button className="search-btn right-btn" onClick={this.onAdd}>
                  <img src="images/page/icon_add.png" alt="" />
                  新增
                </Button>
                <div className="search">
                  <span className="label">
                      角色:
                  </span>
                  <Select
                    style={{ width: 260 }}
                    placeholder="请选择"
                    onChange={this.selectRoles.bind(this)}
                  >
                    {
                      this.state.roleList.map((item) => {
                        return (<Option key={item.id} >{item.name}</Option >);
                      })
                    }
                  </Select>
                  <Search
                    placeholder="查询"
                    onSearch={this.handleSearch.bind(this)}
                  />
                </div>
              </div>
              <div className="content">
                <Spin size="large" spinning={this.state.isLoading} tip="加载中...">
                  <Table
                    className="account-manager-table"
                    rowKey={record => record.id}
                    columns={columns}
                    bordered
                    dataSource={this.state.data}
                    pagination={{
                      pageSize: PAGE_SIZE,
                      total: this.state.dataCount,
                      current: this.state.listPage,
                      onChange: this.onListPageChange.bind(this)
                    }}
                  />
                </Spin>
              </div>
            </div>
          }
        />
        <AddModal
          ref={(ref) => { this.AddModal = ref; }}
          onOk={this.initList}
        />
        <InitialModal
          ref={(ref) => { this.InitialModal = ref; }}
        />
      </div>
    );
  }
}

export default Account;
